package com.mec.offload.controller;

import com.alibaba.fastjson.JSON;
import com.mec.offload.model.LicensePlate;
import com.mec.offload.service.LicensePlateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@Controller
@CrossOrigin
@RequestMapping(value = "/offload/baidu", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public class CarIdentificationController {
    public String licensePlate;

    @Autowired
    private LicensePlateService licensePlateService;

    //@CrossOrigin(origins = "*")
    @RequestMapping("/")
    @ResponseBody
    public LicensePlate findLicensePlate(String licensePlate) {
//        //String chepai;
//        Map<String, Object> map1 = new HashMap<>();
//        // 获取token
//        String accessToken = AccessToken.getAuth();
//        // 通用识别url
//        String otherHost = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic";//通用识别图片文字的URL
//        try {
//            //读取本地图片输入流
//            FileInputStream inputStream = new FileInputStream("C:\\Users\\wsy_b\\Desktop\\chepai2.jpg");
//            String base = Base64.encodeBase64String(IOUtils.toByteArray(inputStream));//将图片换成base64编码
//            Logger logger = LoggerFactory.getLogger(CarIdentificationController.class);
//            //logger.info(base);
//            logger.info("图片的base64码;" + base);
//            String params = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(base, "UTF-8");
//            /**
//             * 线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
//             */
////            String accessToken = "#####调用鉴权接口获取的token#####";
//            String result = HttpUtil.post(otherHost, accessToken, params);
//            JSONObject jsonObject = JSONObject.parseObject(result);
//            JSONArray words_result = (JSONArray) jsonObject.get("words_result");
//            JSONObject o = (JSONObject) words_result.get(0);
//            //添加
//            JSONObject o1 = (JSONObject) words_result.get(1);
//            //
//            map1.put("license", o.get("words"));
//            System.out.println(result);
//            //添加
//            System.out.println("words:");
//            System.out.println(o1.get("words"));
//            licensePlate = o1.get("words").toString();
//            System.out.println("试试啊啊啊啊啊啊啊啊啊啊啊啊啊");
//            System.out.println(licensePlate);
//            licensePlateService.findLicensePlate(licensePlate);
//            System.out.print(licensePlateService.findLicensePlate(licensePlate));
//
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        //return map1;
//        System.out.println("试试啊啊啊啊啊啊啊啊啊啊啊啊啊");
//        System.out.print(licensePlateService.findLicensePlate(licensePlate));
//        System.out.println("试试啊啊啊啊啊啊啊啊啊啊啊啊啊");
//        return licensePlateService.findLicensePlate(licensePlate);
        return null;
    }


    //@CrossOrigin(origins = "*")
    @RequestMapping("/chepai")
    @ResponseBody
    public List<LicensePlate> getAllLicensePlate() {
        try {
            licensePlateService.getAllLicensePlate();
            for (int i = 0; i < licensePlateService.getAllLicensePlate().size(); i++)
                System.out.print(licensePlateService.getAllLicensePlate().get(i));
            return licensePlateService.getAllLicensePlate();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("error");
        return null;
    }


    //@CrossOrigin(origins = "*")
    @RequestMapping("/imageUpload")
    @ResponseBody
    public Map imageUpload(@RequestParam("fileName") MultipartFile file) {
        String result_msg = "";//上传结果信息

        Map<String, Object> root = new HashMap<String, Object>();

        if (file.getSize() / 1000 > 100) {
            result_msg = "图片大小不能超过100KB";
        } else {
            //判断上传文件格式
            String fileType = file.getContentType();
            if (fileType.equals("image/jpeg") || fileType.equals("image/png") || fileType.equals("image/jpeg")) {
                // 要上传的目标文件存放的绝对路径
                //用src为保存绝对路径不能改名只能用原名，不用原名会导致ajax上传图片后在前端显示时出现404错误-->原因未知
//                String localPath="F:\\IDEAProject\\imageupload\\src\\main\\resources\\static\\img";
                final String localPath = "C:\\Users\\wsy_b\\Pictures\\img";
                //上传后保存的文件名(需要防止图片重名导致的文件覆盖)
                //获取文件名
                String fileName = file.getOriginalFilename();
                //获取文件后缀名
                String suffixName = fileName.substring(fileName.lastIndexOf("."));
                //重新生成文件名
                fileName = UUID.randomUUID() + suffixName;
                if (upload(file, localPath, fileName)) {
                    //文件存放的相对路径(一般存放在数据库用于img标签的src)
                    String relativePath = "img/" + fileName;
                    root.put("relativePath", relativePath);//前端根据是否存在该字段来判断上传是否成功
                    result_msg = "图片上传成功";
                } else {
                    result_msg = "图片上传失败";
                }
            } else {
                result_msg = "图片格式不正确";
            }
        }

        root.put("result_msg", result_msg);

//        JSON.toJSONString(root,SerializerFeature.DisableCircularReferenceDetect);
        String root_json = JSON.toJSONString(root);
        System.out.println(root_json);
        return root;
    }
    public static boolean upload(MultipartFile file, String path, String fileName) {

        //确定上传的文件名
        String realPath = path + "\\" + fileName;
        System.out.println("上传文件：" + realPath);

        File dest = new File(realPath);

        //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }

        try {
            //保存文件
            file.transferTo(dest);
            return true;
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }
}



